package service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import model.DAOPersist;
import model.History;
import model.Persistence;
import model.Person;
import model.SaleData;
import tools.Util;
import converter.BeanJsonConverter;

public class FriendSale {

	private static final Logger logger = Logger.getLogger(FriendSale.class.getName());

	public static final String OK = "200";
	public static final String FAIL = "400";
	public static Map<String, SaleData> userdata = new HashMap<String, SaleData>();
	public static BeanJsonConverter converter = new BeanJsonConverter();

	public static Persistence persist = DAOPersist.get();
	/**
	 * initialize the user sales data
	 * 
	 * @param uid
	 * @return
	 */
	private static SaleData init(String uid) {

		try {
			SaleData data = new SaleData();
			
			data.setId(Util.getId(uid));
			data.setDomain(Util.getDomain(uid));
			data.setCash(10000);
			data.setPrice(500);
			data.setHistory(new ArrayList<History>());
			data.setSlaves(new ArrayList<String>());
			data.setNickname("");
			data.setBuyUntil(new Date());

			userdata.put(uid, data);
			logger.info(uid + " had initialized.");
			return data;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * store user data,only need name and thumbnail
	 * 
	 * @param uid
	 * @param name
	 * @param thumbnail
	 * @return
	 */
	public static String init(String uid, String name, String thumbnail) {
		SaleData sdata = getDataObj(uid);
		if (sdata == null) {
			sdata = init(uid);
		}

		Person p = sdata.getPerson();
		if (p == null) {
			p = new Person();
		}
		p.setId(sdata.getId());
		p.setName(name);
		p.setThumbnail(thumbnail);
		sdata.setPerson(p);
		return OK;
	}

	// combine post userdata and return user data
	/**
	 * retrieve user sale data and update user info
	 * 
	 * @return json object of user sale data
	 */
	public static String getData(String uid, String name, String thumbnail,
			String gender) {
		init(uid, name, thumbnail);
		SaleData data = getDataObj(uid);
		Map<String, SaleData> retdata = new HashMap<String, SaleData>();
		retdata.put(Util.getId(uid), data);
		return converter.convertToString(retdata);
	}

	/**
	 * 
	 * @param uid
	 * @return SaleData object
	 */
	public static SaleData getDataObj(String uid) {
		return userdata.get(uid);
	}

	public static String buy(String masterid, String slaveid, String nickname) {
		SaleData masterdata = getDataObj(masterid);
		SaleData slavedata = getDataObj(slaveid);
		// check if already has this slave
		if (isSlave(masterid, slaveid)) {
			return "你已经买了这个奴隶.";
		}
		if (isSlave(slaveid, masterid)) {
			return "你不能买你的主人";
		}

		int slaveprice = slavedata.getPrice();
		int cash = masterdata.getCash();
		if (cash < slaveprice) {
			return "你的钱不够哦,攒够了钱再来吧.";
		}

		// check if slave is working.
		Date buyuntil = slavedata.getBuyUntil();
		Date now = new Date();
		if (now.before(buyuntil)) {
			return "奴隶" + slavedata.getPerson().getName() + "正在"
					+ slavedata.getStatus() + "," + slavedata.displayBuyUntil()
					+ " 之前不能被买卖.";
		}

		String history = buyHistory(masterdata, slavedata, nickname, slaveprice);

		cash = cash - slaveprice;
		masterdata.setCash(cash);
		masterdata.getSlaves().add(slaveid);

		int profit = (int) (slavedata.getPrice() / 1.1 * 0.05);
		if (slavedata.getMaster() != null) {
			SaleData oldmaster = getDataObj(slavedata.getMaster().getId());
			oldmaster.setCash(oldmaster.getCash() + profit);
			oldmaster.getHistory()
					.add(new History("你赚了¥" + profit, new Date()));
			oldmaster.getSlaves().remove(slavedata.getId());
		}

		slavedata.setPrice((int) (slavedata.getPrice() * 1.1));
		slavedata.setCash(slavedata.getCash() + profit);
		slavedata.setMaster(masterdata.getPerson());
		slavedata.setNickname(nickname);
		slavedata.getHistory().add(new History("你赚了¥" + profit, new Date()));

		return history;
	}

	public static String dostuff(String viewerid, String targetid,
			String stuffid) {
		SaleData masterdata = getDataObj(viewerid);
		SaleData targetdata = getDataObj(targetid);
		String result = Stuff.execute(masterdata, targetdata, stuffid);

		return result;
	}

	/**
	 * check relationship
	 * 
	 * @param master
	 * @param slave
	 * @return
	 */
	public static boolean isSlave(String master, String slave) {
		SaleData masterdata = getDataObj(master);
		SaleData slavedata = getDataObj(slave);

		return isSlave(masterdata, slavedata);
	}

	public static boolean isSlave(SaleData master, SaleData slave) {
		return master.getSlaves().contains(slave.getId());
	}

	public static String buyHistory(SaleData masterdata, SaleData slavedata,
			String nickname, int price) {
		Date time = new Date();
		String history = "[" + masterdata.getId() + "]以¥" + price + "的价格";
		SaleData oldmaster = null;
		if (slavedata.getMaster() != null) {
			oldmaster = getDataObj(slavedata.getMaster().getId());
			history += "从[" + oldmaster.getId() + "]手里";
		}
		history += "买了[" + slavedata.getId() + "]";
		if (nickname != null && !nickname.equals("")) {
			history += ",并起了个绰号叫\"" + nickname + "\"";
		}

		history += ".";
		History h = new History(history, time);

		masterdata.getHistory().add(h);
		slavedata.getHistory().add(h);
		if (oldmaster != null)
			oldmaster.getHistory().add(h);

		return h.displayText(Util.convertToGlobal(masterdata.getDomain(),masterdata.getId()));
	}
	
	public static List<SaleData> sortByPrice(){
		List<SaleData> s = new ArrayList<SaleData>();
		s.addAll(userdata.values());
		Collections.sort(s, new SaleDataPriceComp());
		return s;
	}
	

	
}
